/*
 *
 * Copyright (c) 2021
 * User:Dybala
 * File:JwtUtils.java
 * Date:2021/11/08 11:13:08
 */

package com.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;


import javax.servlet.http.HttpServletRequest;
import java.util.Date;

public class JwtUtils {
    // Token过期时间30分钟（用户登录过期时间是此时间的两倍，以token在reids缓存时间为准）
    public static final long EXPIRE_TIME = 30 * 60 * 1000;
    static String secret="123456";
    /**
     * 校验token是否正确
     * @param token  密钥
     * @return 是否正确
     */
    public static boolean verify(String token, String email) {
        try {
            // 根据id生成JWT效验器
            Algorithm algorithm = Algorithm.HMAC256(secret);
            JWTVerifier verifier = JWT.require(algorithm).withClaim("email", email).build();
            // 效验TOKEN
            DecodedJWT jwt = verifier.verify(token);
            return true;
        } catch (Exception exception) {
            return false;
        }
    }

    /**
     * 获得token中的信息无需secret解密也能获得
     * @return token中包含email
     */
    public static String getEmail(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("email").asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 生成签名,30min后过期
     */
    public static String sign(String email) {
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        //使用HS256生成token,密钥则是指定的密码
        Algorithm algorithm = Algorithm.HMAC256(secret);
        // 附带ID信息
        return JWT.create().withClaim("email", email).withExpiresAt(date).sign(algorithm);
    }

    /**
     * 根据request中的token获取用户email
     * @param request
     * @return
     */
    public static String getIDByToken(HttpServletRequest request) {
        String accessToken = request.getHeader("token");
        String email = getEmail(accessToken);
        if (email==null) {
            throw new RuntimeException("无法获取有效用户！");
        }
        return email;
    }
}
